package com.paul.sys.tools.dbutil.dialect;

import com.paul.sys.tools.CommPageBean;
import com.paul.sys.tools.dbutil.mapper.builder.SqlBuilder;
import org.apache.ibatis.builder.SqlSourceBuilder;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.CachingExecutor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

/**
 * 采用分页拦截器执行物理分页查询时，原生的Executor创建cacheKey时未能包含分页参数page，为了解决这个问题，创建了本拦截器，
 * 本拦截器会拦截CachingExecutor的query方法，在创建cacheKey时将分页参数page包含其中。 老规矩，签名里要拦截的类型只能是接口。
 * 
 * 
 */
@Intercepts({@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class CacheInterceptor implements Interceptor {
    private static final Log logger = LogFactory.getLog(CacheInterceptor.class);
    
    private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
    private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
    private static String defaultPageSqlId = ".*Page$"; // 需要拦截的ID(正则匹配)
    private static String pageSqlId = ""; // 需要拦截的ID(正则匹配)

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Executor executorProxy = (Executor) invocation.getTarget();
        MetaObject metaExecutor = MetaObject.forObject(executorProxy, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY);
        // 分离代理对象链
        while (metaExecutor.hasGetter("h")) {
            Object object = metaExecutor.getValue("h");
            metaExecutor = MetaObject.forObject(object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY);
        }
        // 分离最后一个代理对象的目标类
        while (metaExecutor.hasGetter("target")) {
            Object object = metaExecutor.getValue("target");
            metaExecutor = MetaObject.forObject(object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY);
        }
        Object[] args = invocation.getArgs();
        
        return this.query(executorProxy.getTransaction().getConnection(), metaExecutor, args);
    }

    public <E> List<E> query(Connection conn, MetaObject metaExecutor, Object[] args) throws SQLException {
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        BoundSql boundSql = ms.getBoundSql(parameterObject);
        CacheKey cacheKey = createCacheKey(conn, ms, parameterObject, rowBounds, boundSql);
        Executor executor = (Executor) metaExecutor.getOriginalObject();
        return executor.query(ms, parameterObject, rowBounds, resultHandler, cacheKey, boundSql);
    }
    
    /**
     * 去除排序带来的性能开销
     * @param sql
     * @return
     */
    private static String cutOrderBySql(String sql) {
    	String SQL = sql.toUpperCase();
    	int orderIdx = SQL.indexOf("ORDER");
    	if (orderIdx == -1) {
    		return sql;
    	}
    	
    	SQL = SQL.substring(orderIdx+5).trim();
    	if (!SQL.startsWith("BY")) {
    		return sql;
    	}
    	
    	int endOrderIdx = SQL.indexOf(")");
    	if (endOrderIdx == -1) {
    		return sql.substring(0, orderIdx).trim();
    	} 
    	
    	return sql.substring(0, orderIdx).trim() + sql.substring(orderIdx+5+endOrderIdx+1);
    }
    

    /**
     * 从数据库里查询总的记录数并计算总页数，回写进分页参数<code>PageParameter</code>,这样调用者就可用通过 分页参数
     * <code>PageParameter</code>获得相关信息。
     * 
     * @param sql
     * @param connection
     * @param mappedStatement
     * @param boundSql
     * @param page
     */
    private void setPageParameter(String sql, Connection connection, MappedStatement mappedStatement,
            BoundSql boundSql, CommPageBean commPageBean) {

    	sql = cutOrderBySql(sql);
    	
    	 // 记录总记录数
        String countSql = "select count(0) as total from (" + sql + ") as t";
        PreparedStatement countStmt = null;
        ResultSet rs = null;
        try {
            countStmt = connection.prepareStatement(countSql);
            BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql,
                    boundSql.getParameterMappings(), boundSql.getParameterObject());
            setParameters(countStmt, mappedStatement, countBS, boundSql.getParameterObject());
            rs = countStmt.executeQuery();
            int totalCount = 0;
            if (rs.next()) {
                totalCount = rs.getInt(1);
            }
            commPageBean.setTotalNum(totalCount);
            int totalPage = totalCount / commPageBean.getPageSize() + ((totalCount % commPageBean.getPageSize() == 0) ? 0 : 1);
            commPageBean.setTotalPage(totalPage);

        } catch (SQLException e) {
        	logger.error("Ignore this exception", e);
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
            	logger.error("Ignore this exception", e);
            }
            try {
                countStmt.close();
            } catch (SQLException e) {
            	logger.error("Ignore this exception", e);
            }
        }

    }
    
    /**
     * 对SQL参数(?)设值
     * 
     * @param ps
     * @param mappedStatement
     * @param boundSql
     * @param parameterObject
     * @throws SQLException
     */
    private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql,
            Object parameterObject) throws SQLException {
        ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, boundSql);
        parameterHandler.setParameters(ps);
    }

    private CacheKey createCacheKey(Connection conn, MappedStatement ms, Object parameterObject, 
    		RowBounds rowBounds, BoundSql boundSql) {
    	
        Configuration configuration = ms.getConfiguration();
        pageSqlId = configuration.getVariables().getProperty("pageSqlId");
        if (null == pageSqlId || "".equals(pageSqlId)) {
            logger.warn("Property pageSqlId is not setted,use default '.*Page$' ");
            pageSqlId = defaultPageSqlId;
        }
        CacheKey cacheKey = new CacheKey();
        cacheKey.update(ms.getId());
        cacheKey.update(rowBounds.getOffset());
        cacheKey.update(rowBounds.getLimit());
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        // 解决自动生成SQL，SQL语句为空导致key生成错误的bug
        if (null == boundSql.getSql() || "".equals(boundSql.getSql())) {
            String id = ms.getId();
            id = id.substring(id.lastIndexOf(".") + 1);
            String newSql = null;
            try {
                if ("select".equals(id)) {
                    newSql = SqlBuilder.buildSelectSql(parameterObject);
                }
                SqlSource sqlSource = buildSqlSource(configuration, newSql, parameterObject.getClass());
                parameterMappings = sqlSource.getBoundSql(parameterObject).getParameterMappings();
                cacheKey.update(newSql);
            } catch (Exception e) {
                logger.error("Update cacheKey error.", e);
            }
        } else {
            cacheKey.update(boundSql.getSql());
        }

        MetaObject metaObject = MetaObject.forObject(parameterObject, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY);

        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                cacheKey.update(parameterObject);
            } else {
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        cacheKey.update(metaObject.getValue(propertyName));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        cacheKey.update(boundSql.getAdditionalParameter(propertyName));
                    }
                }
            }
        }
        // 当需要分页查询时，将page参数里的当前页和每页数加到cachekey里
        if (ms.getId().matches(pageSqlId) && metaObject.hasGetter("page")) {
            CommPageBean page = (CommPageBean) metaObject.getValue("page");
            if (null != page) {
                cacheKey.update(page.getCurPage());
                cacheKey.update(page.getPageSize());

                // 重设分页参数里的总页数等
                setPageParameter(boundSql.getSql(), conn, ms, boundSql, page);
            }
        }
        return cacheKey;
    }

    /**
     * 只拦截CachingExecutor，其他的直接返回目标本身
     */
    @Override
    public Object plugin(Object target) {
        if (target instanceof CachingExecutor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {

    }

    private SqlSource buildSqlSource(Configuration configuration, String originalSql, Class<?> parameterType) {
        SqlSourceBuilder builder = new SqlSourceBuilder(configuration);
        return builder.parse(originalSql, parameterType, null);
    }

}

